package hibernate;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.hibernate.FetchMode;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.type.Type;

public class DaoHelper {
	
	
	public static DetachedCriteria includeClass(Class clasz,String... includes){
		
		DetachedCriteria dc = DetachedCriteria.forClass(clasz);
		if(includes!=null){
			for (String propertyName : includes) {
				dc.setFetchMode(propertyName, FetchMode.JOIN);
			}
		}
		return dc;
	}
			
	
	public static DetachedCriteria forClass(Class clasz, String orderBy,
			boolean isAsc, String sqlWhere, String... includes) {
		DetachedCriteria dc = includeClass(clasz,includes);
		if (!StringUtils.isEmpty(sqlWhere)) {
			dc.add(Restrictions.sqlRestriction(sqlWhere));
		}
		if (isAsc) 
			dc.addOrder(Order.asc(orderBy));
		else 
			dc.addOrder(Order.desc(orderBy));
		return dc;
	}

	public static Type[] getTypes(Object[] obj) {
		Type[] types = new Type[obj.length];

		for (int i = 0; i < types.length; i++) {
			types[i] = getType(obj);
		}
		return types;
	}

	public static Type getType(Object t) {
		if (t instanceof Integer) {
			return Hibernate.INTEGER;
		}
		if (t instanceof String) {
			return Hibernate.STRING;
		}
		if (t instanceof Date) {
			return Hibernate.DATE;
		}
		if (t instanceof Long) {
			return Hibernate.LONG;
		}
		if (t instanceof Double) {
			return Hibernate.DOUBLE;
		}
		if (t instanceof Float) {
			return Hibernate.FLOAT;
		}
		throw new HibernateException("");
	}
}
